'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 角色
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var moment = require('moment');
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var dataApi = require('../libs/dataApi');
var constantUtil = require('../util/constantUtil');
var envUtil = require('../util/envUtil');
var roleMgr = require('../mgr/roleMgr');
var vipConf = require('../config/vipConf.js');
var talentSchema = require('../schemas/talent/talentSchema.js');

/**
 * 初始化农民个数
 * @return {[type]} [description]
 */
var _initWorkerNum = function () {
    return constantUtil.value('start_worker_num');
};

/**
 * 初始化金币
 * @return {[type]} [description]
 */
var _initGold = function () {
    return constantUtil.value('start_gold');
};

/**
 * 初始化粮食
 * @return {[type]} [description]
 */
var _initFood = function () {
    return constantUtil.value('start_food');
};

/**
 * 初始化钻石
 * @return {[type]} [description]
 */
var _initDiamond = function () {
    return constantUtil.value('start_point');
};

/**
 * 初始化保护时间
 * @return {[type]} [description]
 */
var _initProtectEndTime = function () {
    return Date.now();
};

/**
 * 初始化体力
 * @return {[type]} [description]
 */
var _initEnergy = function () {
    return constantUtil.value('sp_start_limit');
};

var _initMagic = function () {
    return constantUtil.value('start_magicka');
};

var _initSoldierSoul = function () {
    return constantUtil.value('start_soldier_soul');
};

var _initDragonGold = function () {
    return constantUtil.value('start_dragon_gold');
};

var _initHarryCount = function () {
    return constantUtil.value('pvp_reward_time_limit');
};

var _initHarryLessCount = function () {
    return constantUtil.value('pvp_lose_star_limit');
};

/**
 * 取出当前日期
 */
var _getThisDay = function () {
    return moment().startOf('day').unix();
};

/**
 * 取出当前日期
 */
var _getNextFive = function () {
    return _getThisDay() + 3600 * 29;
};

/**
 * 初始禁言时间
 * @return {[type]} [description]
 */
var _initBanSendTime = function () {
    return moment().unix();
};

var _initLogoutTime = function () {
    return moment();
};

/**
 * 初始英雄天赋
 * @return {[type]} [description]
 */
var _initHeroTalent = function () {
    var info_list = [];
    dataApi.hero_talent.each(function (hero_talent_conf, hero_talent_id) {
        info_list.push({
            talent_id: hero_talent_id,
            open_talent_status: 1
        });
    });
    return info_list;
};

/**
 * 角色
 */
var roleSchema = new mongoose.Schema({
    // 玩家id
    uid: {
        type: Number,
        required: true
    },

    // 玩家昵称
    channel_id: {
        type: String,
        required: true,
    },

    // 角色id
    role_id: {
        type: Number,
        required: true,
        index: true
    },

    // 职业
    job_type: {
        type: Number,
        required: true
    },

    // 玩家等级
    lv: {
        type: Number,
        default: 1,
        index: true
    },

    // 已同步到角色等级
    sync_lv: {
        type: Number,
        default: 0
    },

    // 玩家经验
    exp: {
        type: Number,
        default: 0
    },

    // 玩家昵称
    name: {
        type: String,
        required: true,
        unique: true
    },

    // 金币
    gold: {
        type: Number,
        default: _initGold
    },

    // 粮食
    food: {
        type: Number,
        default: _initFood
    },

    // 兵魂
    soldier_soul: {
        type: Number,
        default: _initSoldierSoul
    },

    // 魔能
    magic: {
        type: Number,
        default: _initMagic
    },

    // 体力
    energy: {
        type: Number,
        default: _initEnergy
    },

    // 体力上限
    energy_max_limit: {
        type: Number,
        default: _initEnergy
    },

    // 科技加体力上限
    tech_add_max_energy: {
        type: Number,
        default: 0
    },

    // vip等级
    vip: {
        type: Number,
        default: 0
    },

    // 钻石
    diamond: {
        type: Number,
        default: _initDiamond
    },

    // 联盟id
    union_id: {
        type: Number,
        default: 0,
        index: true
    },

    // 联盟名
    union_name: {
        type: String,
        default: ''
    },

    // 聯盟旗幟
    union_flag: {
        type: Number,
        default: 0
    },

    // 龙币
    dragon_gold: {
        type: Number,
        default: _initDragonGold
    },

    // 工人数
    worker: {
        type: Number,
        default: _initWorkerNum
    },

    // 购买工人结时间
    buy_worker_end_tm: {
        type: Number,
        default: 0
    },

    // 粮食购买次数
    buy_food_times: {
        type: Number,
        default: 0
    },

    // 金币购买次数
    buy_gold_times: {
        type: Number,
        default: 0
    },

    // 保护时间
    protect_end_time: {
        type: Date,
        default: _initProtectEndTime
    },

    // 免费领取粮食时间
    last_food_recieve_time: {
        type: Date,
        default: 0
    },

    // 最后登入时间
    last_login_time: {
        type: Date,
        default: 0
    },

    // 上次回复体力时间
    last_recover_time: {
        type: Date,
        default: Date.now
    },

    // 最后登出时间
    last_logout_time: {
        type: Date,
        default: _initLogoutTime
    },

    // 创建角色时间
    create_time: {
        type: Date,
        default: Date.now
    },

    // 购买体力次数
    buy_sp_num: {
        type: Number,
        default: 0
    },

    // 英雄战力
    hero_power: {
        type: Number,
        default: 0
    },

    // 总战力
    main_power: {
        type: Number,
        default: 0
    },

    // 掠夺奖励资源剩余次数
    harry_count: {
        type: Number,
        default: _initHarryCount
    },

    // 掠夺奖励龙币剩余次数
    harry_dragon_count: {
        type: Number,
        default: _initHarryCount
    },

    // 掠夺降星剩余次数
    harry_less_count: {
        type: Number,
        default: _initHarryLessCount
    },

    // 爵位
    noble: {
        type: Number,
        default: 1
    },

    // 繁荣度
    prosperous: {
        type: Number,
        default: 100
    },

    // 受保护的繁荣度
    protect_prosperous: {
        type: Number,
        default: 0
    },

    // 繁荣度保护结束时间
    protect_prosperous_end: {
        type: Number,
        default: 0
    },

    // 新手标志
    recruits: {
        type: Number,
        default: 0
    },

    // 最后刷新繁荣度时间
    last_refresh_properous_time: {
        type: Number,
        default: 0
    },

    // 军功
    honor: {
        type: Number,
        default: 0
    },

    // 累计充值钻石
    pay_diamond: {
        type: Number,
        default: 0
    },

    // vip经验
    vip_exp: {
        type: Number,
        default: 0
    },

    // 已领取累计充值礼包
    total_pay_picked: {
        type: [Number],
        default: []
    },

    // 每日累计充值
    daily_pay: {
        type: Number,
        default: 0
    },

    // 累计充值
    total_pay: {
        type: Number,
        default: 0
    },

    // 已领取每日累计充值礼包
    daily_pay_picked: {
        type: [Number],
        default: []
    },

    // 累计充值天数
    total_pay_day: {
        type: Number,
        default: 0
    },

    // 累计充值天数
    last_pay_day: {
        type: Number,
        default: 0
    },

    // 已领取累计充值天数奖励
    total_pay_day_picked: {
        type: [Number],
        default: []
    },

    // 已领取全服红包列表
    red_packet_picked: {
        type: [Number],
        default: []
    },

    // 禁言时间截至
    ban_send_time: {
        type: Number,
        default: _initBanSendTime
    },

    // 是否永久禁言状态
    permanent_ban_send_state: {
        type: Number,
        default: 0
    },

    // 英雄天赋
    hero_talent: {
        type: [talentSchema],
        default: _initHeroTalent
    },

    // 当前选中天赋技能id
    choice_talent: {
        type: Number,
        default: 1
    },

    // 下次数据刷新日期
    next_refresh_day: {
        type: Number,
        default: 0
    },

    // 副本当前总星数
    total_copy_star_num: {
        type: Number,
        default: 0
    },

    // 英雄星座等级
    constellation_lv: {
        type: Number,
        default: 0
    },

    // 下次5点刷新时间
    next_five_refresh: {
        type: Number,
        default: 0
    }
});

/**
 * 清除新手标志
 * @return {[type]} [description]
 */
roleSchema.methods.setRecruits = function () {
    this.recruits = 0;
};

/**
 * 获取英雄天赋列表
 * @return {[type]} [description]
 */
roleSchema.methods.getHeroTalentList = function () {
    return this.hero_talent;
};

/**
 * 当前英雄天赋
 * @return {[type]} [description]
 */
roleSchema.methods.getHeroTalent = function () {
    return this.choice_talent;
};

/**
 * 切换英雄天赋
 * @return {[type]} [description]
 */
roleSchema.methods.setHeroTalent = function (talent_id) {
    var is_valid = false;
    _.some(this.getHeroTalentList(), function (value) {
        if (value.talent_id == talent_id && value.open_talent_status >= 1) {
            is_valid = true;
            return true;
        }
    });
    if (!!is_valid) {
        this.choice_talent = talent_id;
    }
    return is_valid;
};

/**
 * 设置副本总星数
 * @return {[type]} [description]
 */
roleSchema.methods.setCopyTotalStar = function (total_star) {
    this.total_copy_star_num = total_star;
};

/**
 * 设置英雄星座等级
 * @return {[type]} [description]
 */
roleSchema.methods.setHeroConstellationLv = function () {
    this.constellation_lv++;
};

/**
 * 获取永久禁言状态
 * @return {[type]} [description]
 */
roleSchema.methods.getPermanentBanSend = function () {
    return this.permanent_ban_send_state;
};

/**
 * 获取禁言时间截止
 * @return {[type]} [description]
 */
roleSchema.methods.getBanSend = function () {
    return this.ban_send_time;
};

/**
 * 设置永久禁言
 * @return {[type]} [description]
 */
roleSchema.methods.setPermanentBanSend = function () {
    this.permanent_ban_send_state = 1;
};

/**
 * 解除永久禁言
 * @return {[type]} [description]
 */
roleSchema.methods.openPermanentBanSend = function () {
    this.permanent_ban_send_state = 0;
};

/**
 * 禁言
 * @return {[type]} [description]
 */
roleSchema.methods.banSend = function (ban_time) {
    this.ban_send_time = ban_time;
};

/**
 * 解禁
 * @return {[type]} [description]
 */
roleSchema.methods.openBanSend = function () {
    this.ban_send_time = _initBanSendTime();
};

/**
 * 获取掠夺免费次数
 * @return {[type]} [description]
 */
roleSchema.methods.getHarryCountTimes = function () {
    return this.harry_count;
};

/**
 * 增加掠夺免费次数
 * @return {[type]} [description]
 */
roleSchema.methods.addHarryCountTimes = function (num) {
    this.harry_count += (+num);
};

/**
 * 添加到已领取累计充值礼包中
 * @return {[type]} [description]
 */
roleSchema.methods.addToTotalPayPicked = function (price) {
    if (_.indexOf(this.total_pay_picked, price) >= 0) {
        return false;
    }
    this.total_pay_picked.push(price);
    return true;
};

/**
 * 添加到已领取每日累计充值礼包中
 * @return {[type]} [description]
 */
roleSchema.methods.addToDailyPayPicked = function (price) {
    if (_.indexOf(this.daily_pay_picked, price) >= 0) {
        return false;
    }
    this.daily_pay_picked.push(price);
    return true;
};

/**
 * 添加到已领取累计充值天数礼包中
 * @return {[type]} [description]
 */
roleSchema.methods.addToTotalPayDayPicked = function (price) {
    if (_.indexOf(this.total_pay_day_picked, price) >= 0) {
        return false;
    }
    this.total_pay_day_picked.push(price);
    return true;
};

/**
 * 添加到已领取全服红包列表中
 * @return {[type]} [description]
 */
roleSchema.methods.addToRedPacketPicked = function (red_packet_id) {
    if (_.indexOf(this.red_packet_picked, red_packet_id) >= 0) {
        return false;
    }
    this.red_packet_picked.push(red_packet_id);
    return true;
};

roleSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 获取体力最大上限
 * @return {[type]} [description]
 */
roleSchema.methods.getEnergyMax = function () {
    return this.energy_max_limit;
};

/**
 * 获取已购买体力次数
 * @return {[type]} [description]
 */
roleSchema.methods.getBuySpNum = function () {
    return this.buy_sp_num;
};

/**
 * 增加已购买体力次数
 * @return {[type]} [description]
 */
roleSchema.methods.addBuySpNum = function () {
    this.buy_sp_num++;
};

/**
 * 刷新繁荣度
 */
roleSchema.methods.refreshProsperous = function () {
    var now_time = moment().unix();
    if (this.protect_prosperous !== 0 && this.protect_prosperous_end < now_time) {
        // 保护期已过，则保护数值清零
        this.protect_prosperous = 0;
    }

    var prosperous_recover_time = constantUtil.value('prosperous_recover_time');
    if (this.last_refresh_properous_time + prosperous_recover_time < now_time) {
        var add_val = Math.floor((now_time - this.last_refresh_properous_time) / prosperous_recover_time);
        this.last_refresh_properous_time += prosperous_recover_time * add_val;
        this.prosperous += add_val;
        if (this.prosperous > 100) {
            this.prosperous = 100;
        }
    }
};

/**
 * 增加繁荣度
 * @return {[type]} [description]
 */
roleSchema.methods.addProsperous = function (add_val) {
    add_val = parseInt(add_val);
    if (add_val < 0) {
        return false;
    }
    this.refreshProsperous();

    this.prosperous += add_val;
    if (this.prosperous > 100) {
        this.prosperous = 100;
    }
    return true;
};

/**
 * 减少繁荣度
 * @return {[type]} [description]
 */
roleSchema.methods.subProsperous = function (sub_val) {
    sub_val = parseInt(sub_val);
    if (sub_val <= 0) {
        return false;
    }
    this.refreshProsperous();

    this.prosperous -= sub_val;

    // 计算繁荣度实际最小值(基础值+保护值)
    var prosperous_min_value = constantUtil.value('prosperous_min_value');
    var real_min_prosperous = prosperous_min_value + this.protect_prosperous;

    // 控制繁荣度最小值
    if (this.prosperous < real_min_prosperous) {
        this.prosperous = real_min_prosperous;
    }
    return true;
};

/**
 * 设置受保护繁荣度
 * @return {[type]} [description]
 */
roleSchema.methods.setProtectProsperous = function (protect_val) {
    if (this.prosperous >= 100) {
        return false;
    }

    // 刷新繁荣度
    this.refreshProsperous();

    // 保存当前基本繁荣度
    var now_time = moment().unix();
    var base_prosperous = this.prosperous;
    if (this.protect_prosperous_end > now_time) {
        base_prosperous -= this.protect_prosperous;
    }

    // 修改繁荣度当前数值
    this.prosperous += protect_val;
    if (this.prosperous > 100) {
        this.prosperous = 100;
    }

    // 设置保护数值
    if (base_prosperous + protect_val > 100) {
        protect_val = 100 - base_prosperous;
    }
    this.protect_prosperous = protect_val;

    var protect_prosperous_length = constantUtil.value('prosperous_protect_time');
    this.protect_prosperous_end = now_time + protect_prosperous_length;

    return true;
};

/**
 * 增加军功
 * @return {[type]} [description]
 */
roleSchema.methods.addHonor = function (add_val) {
    add_val = parseInt(add_val);
    if (add_val <= 0) {
        return false;
    }
    this.honor += add_val;
    return true;
};

/**
 * 减少军功
 * @return {[type]} [description]
 */
roleSchema.methods.subHonor = function (sub_val) {
    sub_val = parseInt(sub_val);
    if (sub_val <= 0) {
        return false;
    }

    this.honor -= sub_val;
    if (this.honor < 0) {
        this.honor = 0;
    }

    return true;
};

/**
 * 获取用户id
 * @return {[type]} [description]
 */
roleSchema.methods.getUid = function () {
    return this.uid;
};

/**
 * 获取角色id
 * @return {[type]} [description]
 */
roleSchema.methods.getRoleId = function () {
    return this.role_id;
};

/**
 * 获取英雄职业
 */
roleSchema.methods.getJob = function () {
    return this.job_type;
};

/**
 * 设置英雄职业
 * @param {[type]} job [description]
 */
roleSchema.methods.setJob = function (job) {
    this.job_type = job;
};

/**
 * 获取英雄等级
 */
roleSchema.methods.getLv = function () {
    return this.lv;
};

/**
 * 添加经验
 */
roleSchema.methods.addExp = function (add_exp, hero_lvl_limit) {
    var self = this;
    this.exp += parseInt(add_exp);
    var hero_lv_item_config = dataApi.hero_lvl.findById(this.lv);
    if (!hero_lv_item_config) {
        return;
    }
    var current_need_exp = hero_lv_item_config.exp;
    var old_lv = this.lv;
    while (this.exp >= current_need_exp && this.lv < hero_lvl_limit) {
        this.exp -= current_need_exp;
        this.lv++;
        hero_lv_item_config = dataApi.hero_lvl.findById(this.lv);
        if (!hero_lv_item_config) {
            return;
        }
        current_need_exp = hero_lv_item_config.exp;
    }

    // 限制满级超经验
    if (this.exp > hero_lv_item_config.exp) {
        this.exp = hero_lv_item_config.exp;
    }

    if (this.exp > current_need_exp) {
        this.exp = current_need_exp;
    }
};

/**
 * 获取名字
 * @return {[type]} [description]
 */
roleSchema.methods.getName = function () {
    return this.name;
};

/**
 * 修改名字
 * @param  {[type]} new_name [description]
 * @return {[type]}          [description]
 */
roleSchema.methods.setName = function (new_name) {
    this.name = new_name;
};

/**
 * 軍團id
 * @param  {[type]} union_id [description]
 * @return {[type]}                  [description]
 */
roleSchema.methods.setUnionId = function (union_id) {
    this.union_id = union_id;
};

/**
 * 获取軍團id
 * @return {[type]}                  [description]
 */
roleSchema.methods.getUnionId = function () {
    return this.union_id;
};

/**
 * 获取金币
 */
roleSchema.methods.getGold = function () {
    return this.gold;
};

/**
 * 添加金币
 */
roleSchema.methods.addGold = function (add_gold) {
    add_gold = parseInt(add_gold);
    if (add_gold > 0) {
        this.gold += add_gold;
        return true;
    }
    return false;
};

/**
 * 扣除金币
 */
roleSchema.methods.subGold = function (sub_gold) {
    sub_gold = parseInt(sub_gold);
    if (this.gold < sub_gold) {
        return false;
    }
    this.gold -= sub_gold;
    return true;
};

/**
 * 获取魔能数量
 */
roleSchema.methods.getMagic = function () {
    return this.magic;
};

/**
 * 增加魔能
 */
roleSchema.methods.addMagic = function (add_magic) {
    add_magic = parseInt(add_magic);
    if (add_magic > 0) {
        this.magic += add_magic;
        return true;
    }
    return false;
};

/**
 * 扣除魔能
 */
roleSchema.methods.subMagic = function (sub_magic) {
    sub_magic = parseInt(sub_magic);
    if (this.magic < sub_magic) {
        return false;
    }
    this.magic -= sub_magic;
    return true;
};

/**
 * 获取兵魂数量
 */
roleSchema.methods.getSoldierSoul = function () {
    return this.soldier_soul;
};

/**
 * 增加兵魂
 */
roleSchema.methods.addSoldierSoul = function (add_soul) {
    add_soul = parseInt(add_soul);
    if (add_soul > 0) {
        this.soldier_soul += add_soul;
        return true;
    }
    return false;
};

/**
 * 扣除兵魂
 */
roleSchema.methods.subSoldierSoul = function (sub_soul) {
    sub_soul = parseInt(sub_soul);
    if (this.soldier_soul < sub_soul) {
        return false;
    }
    this.soldier_soul -= sub_soul;
    return true;
};

/**
 * 获取粮食
 */
roleSchema.methods.getFood = function () {
    return this.food;
};

/**
 * 添加粮食
 */
roleSchema.methods.addFood = function (add_food) {
    add_food = parseInt(add_food);
    this.food += add_food;
};

/**
 * 扣除粮食
 */
roleSchema.methods.subFood = function (sub_food) {
    sub_food = parseInt(sub_food);
    if (this.food < sub_food) {
        return false;
    }
    this.food -= sub_food;
    return true;
};

/**
 * 添加钻石
 */
roleSchema.methods.addDiamond = function (add_diamond) {
    add_diamond = parseInt(add_diamond);
    this.diamond += add_diamond;
};

/**
 * 添加充值钻石
 * @return {[type]} [description]
 */
roleSchema.methods.addPayDiamond = function (add_diamond) {
    add_diamond = +add_diamond;
    this.diamond += add_diamond;

    this.pay_diamond += add_diamond;
    this.vip_exp += add_diamond;
    var now_pay_day = moment().startOf('day').unix();
    if (now_pay_day > this.last_pay_day) {
        this.total_pay_day++;
        this.last_pay_day = now_pay_day;
    }

    this.resetVip();
};

/**
 * 添加充值金额
 * @return {[type]} [description]
 */
roleSchema.methods.addPayVal = function (pay_val) {
    this.daily_pay += +pay_val;
    this.total_pay += +pay_val;
};

/**
 * 添加vip经验
 * @return {[type]} [description]
 */
roleSchema.methods.addVipExp = function (add_val) {
    add_val = +add_val;

    this.vip_exp += add_val;
    this.resetVip();
};

/**
 * 获取钻石
 */
roleSchema.methods.getDiamond = function () {
    return this.diamond;
};

/**
 * 扣除钻石
 */
roleSchema.methods.subDiamond = function (sub_diamond) {
    if (this.diamond < sub_diamond) {
        return false;
    }
    this.diamond -= +sub_diamond;
    return true;
};

/**
 * 获取龙币
 * @return {[type]} [description]
 */
roleSchema.methods.getDragonGold = function () {
    return this.dragon_gold;
};

/**
 * 增加龙币
 * @param {[type]} add_dragon_gold [description]
 */
roleSchema.methods.addDragonGold = function (add_dragon_gold) {
    this.dragon_gold += (+add_dragon_gold);
};

/**
 * 扣除龙币
 * @param {[type]} sub_dragon_gold [description]
 */
roleSchema.methods.subDragonGold = function (sub_dragon_gold) {
    sub_dragon_gold = parseInt(sub_dragon_gold);
    if (this.dragon_gold < sub_dragon_gold) {
        return false;
    }
    this.dragon_gold -= sub_dragon_gold;
    return true;
};

/**
 * 获取体力
 * @return {[type]} [description]
 */
roleSchema.methods.getEnergy = function () {
    return this.energy;
};

/**
 * 增加体力
 * @param {[type]} add_physical [description]
 */
roleSchema.methods.addEnergy = function (add_energy) {
    this.energy += (+add_energy);
};

/**
 * 扣除体力
 * @param {[type]} sub_physical [description]
 */
roleSchema.methods.subEnergy = function (sub_energy) {
    sub_energy = parseInt(sub_energy);
    if (this.energy < sub_energy) {
        return false;
    }
    var full_energy = (this.energy >= this.energy_max_limit);
    this.energy -= sub_energy;
    if (full_energy && this.energy < this.energy_max_limit) {
        this.last_recover_time = moment();
    }

    return true;
};

/**
 * 获取工人个数
 */
roleSchema.methods.getWorker = function () {
    var worker = this.worker;
    if (this.buy_worker_end_tm >= moment().unix()) {
        worker++;
    }
    return worker;
};

/**
 * 延长购买建造队列时间
 */
roleSchema.methods.addBuyBuildScheduleTime = function () {
    var self = this;
    var now_tm = moment().unix();
    if (self.buy_worker_end_tm < now_tm) {
        self.buy_worker_end_tm = now_tm;
    }
    self.buy_worker_end_tm += constantUtil.value('worker_last_time');
};

/**
 * 添加工人
 */
roleSchema.methods.addWorker = function () {
    this.worker++;
};

/**
 * 添加金币购买次数
 */
roleSchema.methods.addBuyGoldTimes = function () {
    this.buy_gold_times++;
};

/**
 * 添加粮食购买次数
 */
roleSchema.methods.addBuyFoodTimes = function () {
    this.buy_food_times++;
};

/**
 * 获取金币购买次数
 */
roleSchema.methods.getBuyGoldTimes = function () {
    return this.buy_gold_times;
};

/**
 * 获取粮食购买次数
 */
roleSchema.methods.getBuyFoodTimes = function () {
    return this.buy_food_times;
};

/**
 * 设置vip
 */
roleSchema.methods.resetVip = function () {
    var vip_exp = this.vip_exp;
    var vip_code = 0;
    dataApi.vip_lvl.each(function (recharge_vip_item) {
        if (vip_exp >= recharge_vip_item.recharge_point) {
            vip_code = recharge_vip_item.id;
        }
    });

    this.vip = vip_code - 1;

    this.resetMaxEnergy();
};

/**
 * 重置vip
 */
roleSchema.methods.resetMaxEnergy = function () {
    var def_energy = constantUtil.value('sp_start_limit');
    var vip_add_max_energy = vipConf.getConf(this.getVip()).add_sp_limit;
    var tech_add_max_energy = this.tech_add_max_energy;
    this.energy_max_limit = def_energy + vip_add_max_energy + tech_add_max_energy;
};

/**
 * 获取vip
 * @return {[type]} [description]
 */
roleSchema.methods.getVip = function () {
    return this.vip;
};

/**
 * 增加保护时间
 * @param {[type]} add_time [description]
 */
roleSchema.methods.addProtectTime = function (add_time) {
    if (this.protect_end_time < moment()) {
        this.protect_end_time = moment().add(add_time, 's');
    } else {
        this.protect_end_time = moment(this.protect_end_time).add(add_time, 's');
    }
};

/**
 * 获取保护时间
 * @param {[type]} add_time [description]
 */
roleSchema.methods.getProtectTime = function () {
    return this.protect_end_time;
};

/**
 * 是否在保护中
 * @return {Boolean} [description]
 */
roleSchema.methods.isProtect = function () {
    return this.protect_end_time > moment();
};

/**
 * 解除保护
 */
roleSchema.methods.removeProtect = function () {
    if (this.protect_end_time > moment()) {
        this.protect_end_time = moment();
    }
};

/**
 * 获取上次登陆的时间
 */
roleSchema.methods.getLastLoginTime = function () {
    return this.last_login_time;
};

/**
 * 获取上次下线的时间
 */
roleSchema.methods.getLastLogoutTime = function () {
    return this.last_logout_time;
};

/**
 * 获取领取粮食的时间
 */
roleSchema.methods.getFoodRecieveTime = function () {
    return this.last_food_recieve_time;
};

/**
 * 获取体力回复的时间
 */
roleSchema.methods.getEnergyRecoverTime = function () {
    return this.last_recover_time;
};

/**
 * 领取粮食的时间
 */
roleSchema.methods.refreshRecieveTime = function () {
    this.last_food_recieve_time = Date.now();
};

/**
 * 重置每日购买次数
 */
roleSchema.methods.resetLimitTime = function () {
    this.buy_food_times = 0;
    this.buy_gold_times = 0;
    this.buy_sp_num = 0;
};

/**
 * 获取创建角色的时间
 * @return {[type]} [description]
 */
roleSchema.methods.getCreateTime = function () {
    return this.create_time;
};

/**
 * 减少掠夺奖励资源次数
 * @return {[type]} [description]
 */
roleSchema.methods.decHarryCnt = function () {
    if (this.harry_count < 1) {
        return false;
    }
    this.harry_count--;
    return true;
};

/**
 * 减少掠夺奖励龙币次数
 * @return {[type]} [description]
 */
roleSchema.methods.decHarryDragonCnt = function () {
    if (this.harry_dragon_count < 1) {
        return false;
    }
    this.harry_dragon_count--;
    return true;
};

/**
 * 减少掠夺降星次数
 * @return {[type]} [description]
 */
roleSchema.methods.decLessHarryCnt = function () {
    if (this.harry_dec_count < 1) {
        return false;
    }
    this.harry_less_count--;
    return true;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
roleSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
roleSchema.methods.push = function () {
    this.pushModify();
};

roleSchema.methods.pushModify = function () {
    roleMgr.sendRoleChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send role message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

roleSchema.plugin(autoIncrement.plugin, {
    model: 'RoleSchema',
    field: 'role_id',
    startAt: 10000
});

if (!roleSchema.options.toJSON) {
    roleSchema.options.toJSON = {};
}
/* jshint unused:false */
roleSchema.options.toJSON.transform = function (doc, ret) {
    ret.protect_end_time = moment(ret.protect_end_time).unix();
    ret.last_recover_time = moment(ret.last_recover_time).unix();
    ret.last_logout_time = moment(ret.last_logout_time).unix();
    delete ret.last_food_recieve_time;
    delete ret.last_login_time;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Role', roleSchema);
